// 三消类游戏逻辑
Page({
  data: {
    board: [], // 8x8 游戏棋盘
    score: 0,
    combo: 0,
    maxCombo: 0,
    movesLeft: 30,
    gameOver: false,
    gameWon: false,
    showHelp: false,
    showComboPopup: false,
    scorePopups: [],
    selectedBlock: null,
    boardSize: 8,
    blockTypes: 6,
    targetScore: 1000,
    // 方块图标
    blockIcons: ['🔴', '🟡', '🟢', '🔵', '🟣', '🟠', '⚪', '⚫']
  },

  onLoad() {
    this.initGame();
  },

  // 初始化游戏
  initGame() {
    this.setData({
      board: this.generateBoard(),
      score: 0,
      combo: 0,
      maxCombo: 0,
      movesLeft: 30,
      gameOver: false,
      gameWon: false,
      selectedBlock: null,
      scorePopups: [],
      showComboPopup: false
    });

    // 确保初始棋盘没有现成的三消组合
    this.removeInitialMatches();
  },

  // 生成随机棋盘
  generateBoard() {
    const board = [];
    for (let i = 0; i < this.data.boardSize; i++) {
      const row = [];
      for (let j = 0; j < this.data.boardSize; j++) {
        const type = Math.floor(Math.random() * this.data.blockTypes) + 1;
        row.push({
          type: type,
          icon: this.data.blockIcons[type - 1],
          selected: false,
          animating: false,
          id: `${i}-${j}-${Date.now()}-${Math.random()}`
        });
      }
      board.push(row);
    }
    return board;
  },

  // 移除初始棋盘中的三消组合
  removeInitialMatches() {
    let hasMatches = true;
    let attempts = 0;
    const maxAttempts = 50;

    while (hasMatches && attempts < maxAttempts) {
      hasMatches = false;
      const board = [...this.data.board];

      for (let row = 0; row < this.data.boardSize; row++) {
        for (let col = 0; col < this.data.boardSize; col++) {
          if (this.hasMatchAt(row, col, board)) {
            // 重新生成这个位置的方块
            const newType = this.getRandomTypeExcluding(row, col, board);
            board[row][col] = {
              ...board[row][col],
              type: newType,
              icon: this.data.blockIcons[newType - 1]
            };
            hasMatches = true;
          }
        }
      }

      this.setData({ board });
      attempts++;
    }
  },

  // 获取一个不会形成三消的随机类型
  getRandomTypeExcluding(row, col, board) {
    const excludeTypes = new Set();

    // 检查水平方向
    if (col >= 2 && board[row][col-1].type === board[row][col-2].type) {
      excludeTypes.add(board[row][col-1].type);
    }

    // 检查垂直方向
    if (row >= 2 && board[row-1][col].type === board[row-2][col].type) {
      excludeTypes.add(board[row-1][col].type);
    }

    let type;
    do {
      type = Math.floor(Math.random() * this.data.blockTypes) + 1;
    } while (excludeTypes.has(type));

    return type;
  },

  // 检查指定位置是否有三消组合
  hasMatchAt(row, col, board) {
    const type = board[row][col].type;

    // 检查水平三消
    if (col >= 2 && board[row][col-1].type === type && board[row][col-2].type === type) {
      return true;
    }

    // 检查垂直三消
    if (row >= 2 && board[row-1][col].type === type && board[row-2][col].type === type) {
      return true;
    }

    return false;
  },

  // 点击方块
  onBlockTap(e) {
    if (this.data.gameOver) return;

    const { row, col } = e.currentTarget.dataset;
    const rowIndex = parseInt(row);
    const colIndex = parseInt(col);

    // 播放点击音效
    this.playClickSound();

    if (this.data.selectedBlock === null) {
      // 第一次点击，选择方块
      this.selectBlock(rowIndex, colIndex);
    } else {
      const { row: selectedRow, col: selectedCol } = this.data.selectedBlock;

      if (selectedRow === rowIndex && selectedCol === colIndex) {
        // 点击同一个方块，取消选择
        this.clearSelection();
      } else if (this.isAdjacent(selectedRow, selectedCol, rowIndex, colIndex)) {
        // 点击相邻方块，尝试交换
        this.attemptSwap(selectedRow, selectedCol, rowIndex, colIndex);
      } else {
        // 点击非相邻方块，重新选择
        this.selectBlock(rowIndex, colIndex);
      }
    }
  },

  // 选择方块
  selectBlock(row, col) {
    // 清除之前的选择
    this.clearSelection();

    // 设置新的选择
    const board = [...this.data.board];
    board[row][col].selected = true;

    this.setData({
      board,
      selectedBlock: { row, col }
    });
  },

  // 清除选择
  clearSelection() {
    if (this.data.selectedBlock) {
      const { row, col } = this.data.selectedBlock;
      const board = [...this.data.board];
      board[row][col].selected = false;

      this.setData({
        board,
        selectedBlock: null
      });
    }
  },

  // 检查两个位置是否相邻
  isAdjacent(row1, col1, row2, col2) {
    const rowDiff = Math.abs(row1 - row2);
    const colDiff = Math.abs(col1 - col2);
    return (rowDiff === 1 && colDiff === 0) || (rowDiff === 0 && colDiff === 1);
  },

  // 尝试交换两个方块
  attemptSwap(row1, col1, row2, col2) {
    // 临时交换
    const board = [...this.data.board];
    const temp = { ...board[row1][col1] };
    board[row1][col1] = { ...board[row2][col2] };
    board[row2][col2] = temp;

    // 检查交换后是否有三消组合
    const matches1 = this.findMatches(row1, col1, board);
    const matches2 = this.findMatches(row2, col2, board);

    if (matches1.length > 0 || matches2.length > 0) {
      // 有效交换
      this.clearSelection();
      this.setData({ board });
      this.consumeMove();
      this.processMatches();
    } else {
      // 无效交换，恢复原状
      this.clearSelection();
      wx.showToast({
        title: '无法形成消除组合',
        icon: 'none',
        duration: 1000
      });
    }
  },

  // 消耗步数
  consumeMove() {
    const movesLeft = this.data.movesLeft - 1;
    this.setData({ movesLeft });

    if (movesLeft <= 0) {
      this.checkGameEnd();
    }
  },

  // 查找指定位置的三消组合
  findMatches(row, col, board = null) {
    if (!board) board = this.data.board;
    const type = board[row][col].type;
    const matches = new Set();

    // 检查水平方向
    const horizontalMatches = this.findHorizontalMatches(row, col, type, board);
    if (horizontalMatches.length >= 3) {
      horizontalMatches.forEach(pos => matches.add(`${pos.row}-${pos.col}`));
    }

    // 检查垂直方向
    const verticalMatches = this.findVerticalMatches(row, col, type, board);
    if (verticalMatches.length >= 3) {
      verticalMatches.forEach(pos => matches.add(`${pos.row}-${pos.col}`));
    }

    return Array.from(matches).map(key => {
      const [r, c] = key.split('-').map(Number);
      return { row: r, col: c };
    });
  },

  // 查找水平方向的匹配
  findHorizontalMatches(row, col, type, board) {
    const matches = [{ row, col }];

    // 向左查找
    for (let c = col - 1; c >= 0 && board[row][c].type === type; c--) {
      matches.unshift({ row, col: c });
    }

    // 向右查找
    for (let c = col + 1; c < this.data.boardSize && board[row][c].type === type; c++) {
      matches.push({ row, col: c });
    }

    return matches;
  },

  // 查找垂直方向的匹配
  findVerticalMatches(row, col, type, board) {
    const matches = [{ row, col }];

    // 向上查找
    for (let r = row - 1; r >= 0 && board[r][col].type === type; r--) {
      matches.unshift({ row: r, col });
    }

    // 向下查找
    for (let r = row + 1; r < this.data.boardSize && board[r][col].type === type; r++) {
      matches.push({ row: r, col });
    }

    return matches;
  },

  // 处理所有匹配
  processMatches() {
    const allMatches = this.findAllMatches();

    if (allMatches.length > 0) {
      this.eliminateMatches(allMatches);
      this.updateScore(allMatches.length);
      this.incrementCombo();

      // 延迟处理下落和填充
      setTimeout(() => {
        this.dropBlocks();
        setTimeout(() => {
          this.fillEmptySpaces();
          setTimeout(() => {
            this.processMatches(); // 递归处理连锁反应
          }, 300);
        }, 300);
      }, 300);
    } else {
      this.resetCombo();
      this.checkGameEnd();
    }
  },

  // 查找棋盘上所有的三消组合
  findAllMatches() {
    const allMatches = new Set();

    for (let row = 0; row < this.data.boardSize; row++) {
      for (let col = 0; col < this.data.boardSize; col++) {
        const matches = this.findMatches(row, col);
        matches.forEach(match => allMatches.add(`${match.row}-${match.col}`));
      }
    }

    return Array.from(allMatches).map(key => {
      const [row, col] = key.split('-').map(Number);
      return { row, col };
    });
  },

  // 消除匹配的方块
  eliminateMatches(matches) {
    const board = [...this.data.board];

    // 标记要消除的方块并添加动画
    matches.forEach(({ row, col }) => {
      board[row][col] = {
        ...board[row][col],
        animating: true,
        eliminating: true
      };

      // 显示分数飞出动画
      this.showScorePopup(row, col, 10);
    });

    this.setData({ board });

    // 播放消除音效和震动
    this.playEliminateSound();

    // 延迟移除方块
    setTimeout(() => {
      const newBoard = [...this.data.board];
      matches.forEach(({ row, col }) => {
        newBoard[row][col] = null; // null 表示空位
      });
      this.setData({ board: newBoard });
    }, 300);
  },

  // 显示分数飞出动画
  showScorePopup(row, col, score) {
    const popup = {
      id: Date.now() + Math.random(),
      x: col * 75 + 37.5, // 根据方块位置计算
      y: row * 75 + 37.5,
      score: score
    };

    const scorePopups = [...this.data.scorePopups, popup];
    this.setData({ scorePopups });

    // 1秒后移除
    setTimeout(() => {
      const newPopups = this.data.scorePopups.filter(p => p.id !== popup.id);
      this.setData({ scorePopups: newPopups });
    }, 1000);
  },

  // 方块下落
  dropBlocks() {
    const board = [...this.data.board];

    for (let col = 0; col < this.data.boardSize; col++) {
      // 收集该列的非空方块
      const nonEmptyBlocks = [];
      for (let row = this.data.boardSize - 1; row >= 0; row--) {
        if (board[row][col] !== null) {
          nonEmptyBlocks.push({
            ...board[row][col],
            animating: false,
            selected: false
          });
        }
      }

      // 清空该列
      for (let row = 0; row < this.data.boardSize; row++) {
        board[row][col] = null;
      }

      // 从底部开始放置非空方块
      for (let i = 0; i < nonEmptyBlocks.length; i++) {
        const targetRow = this.data.boardSize - 1 - i;
        board[targetRow][col] = {
          ...nonEmptyBlocks[i],
          id: `${targetRow}-${col}-${Date.now()}-${Math.random()}`
        };
      }
    }

    this.setData({ board });
  },

  // 填充空白位置
  fillEmptySpaces() {
    const board = [...this.data.board];

    for (let col = 0; col < this.data.boardSize; col++) {
      for (let row = 0; row < this.data.boardSize; row++) {
        if (board[row][col] === null) {
          const type = Math.floor(Math.random() * this.data.blockTypes) + 1;
          board[row][col] = {
            type: type,
            icon: this.data.blockIcons[type - 1],
            selected: false,
            animating: true,
            id: `${row}-${col}-${Date.now()}-${Math.random()}`
          };
        }
      }
    }

    this.setData({ board });

    // 移除动画标记
    setTimeout(() => {
      const newBoard = [...this.data.board];
      for (let row = 0; row < this.data.boardSize; row++) {
        for (let col = 0; col < this.data.boardSize; col++) {
          if (newBoard[row][col]) {
            newBoard[row][col].animating = false;
          }
        }
      }
      this.setData({ board: newBoard });
    }, 300);
  },

  // 更新分数
  updateScore(blocksCount) {
    const basePoints = blocksCount * 10;
    const comboBonus = this.data.combo > 1 ? this.data.combo * 5 : 0;
    const totalPoints = basePoints + comboBonus;

    const newScore = this.data.score + totalPoints;
    this.setData({ score: newScore });

    // 检查是否达到目标分数
    if (newScore >= this.data.targetScore) {
      this.setData({ gameWon: true });
      setTimeout(() => {
        this.setData({ gameOver: true });
      }, 1000);
    }
  },

  // 增加连击
  incrementCombo() {
    const newCombo = this.data.combo + 1;
    const maxCombo = Math.max(this.data.maxCombo, newCombo);

    this.setData({
      combo: newCombo,
      maxCombo: maxCombo
    });

    // 显示连击提示
    if (newCombo > 1) {
      this.showComboPopup();
    }
  },

  // 重置连击
  resetCombo() {
    this.setData({ combo: 0 });
  },

  // 显示连击提示
  showComboPopup() {
    this.setData({ showComboPopup: true });
    setTimeout(() => {
      this.setData({ showComboPopup: false });
    }, 1000);
  },

  // 检查游戏结束
  checkGameEnd() {
    // 如果已经获胜，不需要检查
    if (this.data.gameWon) return;

    // 如果步数用完
    if (this.data.movesLeft <= 0) {
      this.setData({ gameOver: true });
      return;
    }

    // 检查是否还有可能的移动
    if (!this.hasPossibleMoves()) {
      // 没有可能的移动，自动洗牌
      this.shuffleBoard();
    }
  },

  // 检查是否有可能的移动
  hasPossibleMoves() {
    for (let row = 0; row < this.data.boardSize; row++) {
      for (let col = 0; col < this.data.boardSize; col++) {
        // 检查与右边方块交换
        if (col < this.data.boardSize - 1) {
          if (this.wouldCreateMatch(row, col, row, col + 1)) {
            return true;
          }
        }

        // 检查与下面方块交换
        if (row < this.data.boardSize - 1) {
          if (this.wouldCreateMatch(row, col, row + 1, col)) {
            return true;
          }
        }
      }
    }
    return false;
  },

  // 检查交换两个位置是否会产生匹配
  wouldCreateMatch(row1, col1, row2, col2) {
    const board = [...this.data.board];

    // 临时交换
    const temp = board[row1][col1];
    board[row1][col1] = board[row2][col2];
    board[row2][col2] = temp;

    // 检查是否有匹配
    const matches1 = this.findMatches(row1, col1, board);
    const matches2 = this.findMatches(row2, col2, board);

    return matches1.length > 0 || matches2.length > 0;
  },

  // 洗牌
  shuffleBoard() {
    wx.showToast({
      title: '自动洗牌中...',
      icon: 'loading',
      duration: 1500
    });

    setTimeout(() => {
      const board = [...this.data.board];
      const allBlocks = [];

      // 收集所有方块
      for (let row = 0; row < this.data.boardSize; row++) {
        for (let col = 0; col < this.data.boardSize; col++) {
          if (board[row][col]) {
            allBlocks.push({
              type: board[row][col].type,
              icon: board[row][col].icon
            });
          }
        }
      }

      // 打乱数组
      for (let i = allBlocks.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [allBlocks[i], allBlocks[j]] = [allBlocks[j], allBlocks[i]];
      }

      // 重新分配到棋盘
      let blockIndex = 0;
      for (let row = 0; row < this.data.boardSize; row++) {
        for (let col = 0; col < this.data.boardSize; col++) {
          if (blockIndex < allBlocks.length) {
            board[row][col] = {
              ...allBlocks[blockIndex],
              selected: false,
              animating: false,
              id: `${row}-${col}-${Date.now()}-${Math.random()}`
            };
            blockIndex++;
          }
        }
      }

      this.setData({ board });
      this.removeInitialMatches();
    }, 1500);
  },

  // 播放点击音效
  playClickSound() {
    wx.vibrateShort({
      type: 'light'
    });
  },

  // 播放消除音效
  playEliminateSound() {
    wx.vibrateShort({
      type: 'medium'
    });
  },

  // 显示帮助
  showHelp() {
    this.setData({ showHelp: true });
  },

  // 隐藏帮助
  hideHelp() {
    this.setData({ showHelp: false });
  },

  // 重新开始游戏
  resetGame() {
    this.initGame();
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});
